/**
 * @describe 时间工具处理
 * @author 游金宇(KM)
 * @date 2023-01-30 11:32:10
 */


/**
 * 
 * @param time 时间(秒)
 * @param fmt 格式
 * @returns 
 */
export const timeFormat = (time: number = 0, fmt = 'hh:mm:ss') => {
    const placeholders = {
        'hh': { regex: /hh|H+/, value: String(Math.floor(time / 3600)).padStart(2, '0') },
        'mm': { regex: /mm|M+/, value: String(Math.floor((time % 3600) / 60)).padStart(2, '0') },
        'ss': { regex: /ss|S+/, value: String(Math.floor(time % 60)).padStart(2, '0') },
    };

    let formattedTime = fmt;

    for (const placeholder in placeholders) {
        const { regex, value } = placeholders[placeholder as keyof typeof placeholders];
        formattedTime = formattedTime.replace(regex, value);
    }

    return formattedTime;
}
/**
 * 时间对象(Date) 时间格式化
 * @param date  时间对象
 * @param fmt   格式化字符(yyyy-MM-dd hh:mm:ss S)
 */
export const format = (date: Date, fmt: string) => {
    var o: any = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        }
    }
    return fmt;
}
/**
 * 获取当前日期函数
 */
export const getNowFormatDate = () => {
    let date = new Date(),
        year = date.getFullYear(), //获取完整的年份(4位)
        month: string | number = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
        strDate: string | number = date.getDate(); // 获取当前日(1-31)
    if (month < 10) month = `0${month}`; // 如果月份是个位数，在前面补0
    if (strDate < 10) strDate = `0${strDate}`; // 如果日是个位数，在前面补0

    return `${year}.${month}.${strDate}`;
}

export type TimeObject = {
    hours: number,
    minutes: number,
    seconds: number,
    milliseconds: number
};

/**
 * 将时间转换为对象 (单位:ms)
 * @param {number} time 
 */
export const convertTimeToObject = (time: number, round: boolean = true): TimeObject => {

    time = round ? Math.round(time / 1000) * 1000 : time

    const hours = Math.floor(time / (3600 * 1000));
    const remainingTimeAfterHours = time % (3600 * 1000);

    const minutes = Math.floor(remainingTimeAfterHours / (60 * 1000));
    const remainingTimeAfterMinutes = remainingTimeAfterHours % (60 * 1000);

    const seconds = Math.floor(remainingTimeAfterMinutes / 1000);

    const milliseconds = round ? Math.round(remainingTimeAfterMinutes % 1000) : remainingTimeAfterMinutes % 1000;

    return {
        hours: hours,
        minutes: minutes,
        seconds: seconds,
        milliseconds: milliseconds
    };
}
